package com.justgame.project.task;

import com.alibaba.fastjson.JSONObject;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.util.FileUtils;
import com.justgame.project.cloud.common.util.RedisUtil;
import com.justgame.project.service.api.dto.SysFileInfoDTO;
import com.justgame.project.service.api.feign.IArtPageInfoClient;
import com.justgame.project.service.api.feign.ISysFileInfoClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.*;


/**
 * 定时刷新任务
 *
 * @Author ZhouWeiBo
 */
@Configuration
@Slf4j
@EnableScheduling
public class RefreshTask {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ISysFileInfoClient sysFileInfoClient;

    @Resource
    private IArtPageInfoClient artPageInfoClient;

    /**
     * 定时清理Redis中未及时使用的文件
     * 每 60 分钟执行一次
     */
    @Async("taskExecutor")
    @Scheduled(fixedRate = 1000 * 60 * 60)
    protected void clearTempFile() {
        try {
            logger.info("正开始清理Redis中过期临时文件！");
            Set<String> listTemps = redisUtil.hKeys(Const.KEY_TEMP_FILES);
            if (listTemps == null || listTemps.size() == 0) {
                logger.info("清理Redis中过期临时文件完毕，共0条！");
                return;
            }
            List<String> clearedFiles = new ArrayList<>();
            listTemps.forEach(key -> {
                /* 获取过期时间 */
                long time = redisUtil.hGet(Const.KEY_TEMP_FILES, key);
                /* 如果超时 */
                if (time <= System.currentTimeMillis()) {
                    /* 删除Hash */
                    redisUtil.hDelete(Const.KEY_CLEARED_FILES, key);
                    /* 暂缓存储到Set */
                    clearedFiles.add(key);
                }
            });

            if (clearedFiles.size() > 0) {
                /* 物理删除文件 */
                FileUtils.deleteFiles(clearedFiles);
                SysFileInfoDTO newDto = new SysFileInfoDTO();
                newDto.setPathList(clearedFiles);
                /* 更新数据库 */
                sysFileInfoClient.deleteFile(newDto);
            }

            logger.info("清理Redis中过期临时文件完毕，共{}条！", clearedFiles.size());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("清理Redis中过期临时文件失败！");
        }
    }

    /**
     * 15分钟一同步ArtPageInfo表中不同Count数据
     */
    @Async("taskExecutor")
    @Scheduled(cron = "0 59 23 * * ?")
    protected void synchronousPageInfoData(){
        log.info("ArtPageInfo表数据同步中...");
        Map<String,Set<ZSetOperations.TypedTuple<Object>>> numMap = new HashMap<>(3);
        Set<ZSetOperations.TypedTuple<Object>> viewNum = redisUtil.zReverseRangeWithScores(Const.KEY_REDIS_WATCH_PAGE_COUNT, 0, 10);
        artPageInfoClient.refreshPageNum(JSONObject.toJSONString(viewNum),Const.KEY_REDIS_WATCH_PAGE_COUNT);
        Set<ZSetOperations.TypedTuple<Object>> likeNum = redisUtil.zReverseRangeWithScores(Const.KEY_REDIS_LIKE_PAGE_COUNT, 0, 10);
        artPageInfoClient.refreshPageNum(JSONObject.toJSONString(likeNum),Const.KEY_REDIS_LIKE_PAGE_COUNT);
        Set<ZSetOperations.TypedTuple<Object>> shareNum = redisUtil.zReverseRangeWithScores(Const.KEY_REDIS_SHARE_PAGE_COUNT, 0, 10);
        artPageInfoClient.refreshPageNum(JSONObject.toJSONString(shareNum),Const.KEY_REDIS_SHARE_PAGE_COUNT);
        log.info("ArtPageInfo表数据同步完毕！");
    }


}
